/**
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

/**
 * @file main.cpp
 */
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <fcntl.h>

#include "acl/acl.h"
#include "aclnn_amp_update_scale.h"

#define SUCCESS 0
#define FAILED 1

#define INFO_LOG(fmt, args...) fprintf(stdout, "[INFO]  " fmt "\n", ##args)
#define WARN_LOG(fmt, args...) fprintf(stdout, "[WARN]  " fmt "\n", ##args)
#define ERROR_LOG(fmt, args...) fprintf(stderr, "[ERROR]  " fmt "\n", ##args)

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

bool ReadFile(const std::string &filePath, size_t fileSize, void *buffer, size_t bufferSize)
{
    struct stat sBuf;
    int fileStatus = stat(filePath.data(), &sBuf);
    if (fileStatus == -1) {
        ERROR_LOG("failed to get file %s", filePath.c_str());
        return false;
    }
    if (S_ISREG(sBuf.st_mode) == 0) {
        ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
        return false;
    }
    std::ifstream file;
    file.open(filePath, std::ios::binary);
    if (!file.is_open()) {
        ERROR_LOG("Open file failed. path = %s", filePath.c_str());
        return false;
    }
    std::filebuf *buf = file.rdbuf();
    size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
    if (size == 0) {
        ERROR_LOG("file size is 0");
        file.close();
        return false;
    }
    if (size > bufferSize) {
        ERROR_LOG("file size is larger than buffer size");
        file.close();
        return false;
    }
    buf->pubseekpos(0, std::ios::in);
    buf->sgetn(static_cast<char *>(buffer), size);
    fileSize = size;
    file.close();
    return true;
}

bool ReadFileEx(const std::string& filename, std::string& result) {
    std::ifstream file(filename);
    if (!file) {
        std::cout << "Failed to open file: " << filename << std::endl;
        return false;
    }

    if (!std::getline(file, result)) {
        std::cout << "Failed to read from file: " << filename << std::endl;
        file.close();
        return false;
    }

    file.close();
    return true;
}

bool WriteFile(const std::string &filePath, const void *buffer, size_t size)
{
    if (buffer == nullptr) {
        ERROR_LOG("Write file failed. buffer is nullptr");
        return false;
    }

    int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
    if (fd < 0) {
        ERROR_LOG("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    auto writeSize = write(fd, buffer, size);
    (void) close(fd);
    if (writeSize != size) {
        ERROR_LOG("Write file Failed.");
        return false;
    }

    return true;
}

int64_t GetShapeSize(const std::vector<int64_t> &shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream *stream)
{
    // 固定写法，acl初始化
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return FAILED);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return FAILED);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return FAILED);

    return SUCCESS;
}

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                    aclDataType dataType, aclTensor **tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // 调用aclrtMalloc申请device侧内存
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return FAILED);

    // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return FAILED);

    // 调用aclCreateTensor接口创建aclTensor
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(),
                              shape.size(), *deviceAddr);
    return SUCCESS;
}

int main(int argc, char **argv)
{
    // 1. （固定写法）device/stream初始化, 参考acl对外接口列表
    // 根据自己的实际device填写deviceId
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return FAILED);

    // 2. 构造输入与输出，需要根据API的接口自定义构造
    std::vector<int64_t> inputXShape = {1, 1};  // current_scale
    std::vector<int64_t> inputYShape = {1, 1};  // growth_tracker
    std::vector<int64_t> inputZShape = {1, 1};  // found_inf
    std::vector<int64_t> outputAShape = {1, 1}; // updated_scale
    std::vector<int64_t> outputBShape = {1, 1}; // updated_growth_tracker

    void *inputXDeviceAddr = nullptr;
    void *inputYDeviceAddr = nullptr;
    void *inputZDeviceAddr = nullptr;    
    void *outputADeviceAddr = nullptr;
    void *outputBDeviceAddr = nullptr;
    aclTensor *inputX = nullptr;
    aclTensor *inputY = nullptr;
    aclTensor *inputZ = nullptr;
    aclTensor *outputA = nullptr;
    aclTensor *outputB = nullptr;
    
    std::vector<float> inputXHostData(inputXShape[0] * inputXShape[1]);
    std::vector<int32_t> inputYHostData(inputYShape[0] * inputYShape[1]);
    std::vector<float> inputZHostData(inputZShape[0] * inputZShape[1]);
    std::vector<float> outputAHostData(outputAShape[0] * outputAShape[1]);
    std::vector<int32_t> outputBHostData(outputBShape[0] * outputBShape[1]);

    //读取数据，给XYZ赋值，这三个是属性growth_factor，backoff_factor，growth_interval
    // char buffer_[512];
    // char* path = getcwd(buffer_, sizeof(buffer_));
    // std::cout << "current path: " << path << std::endl;

    size_t fileSize = 0;
    void ** input1=(void **)(&inputXHostData);
    void ** input2=(void **)(&inputYHostData);
    void ** input3=(void **)(&inputZHostData);
    ReadFile("../input/input_x.bin", fileSize, *input1, (size_t)(inputXShape[0] * inputXShape[1] * sizeof(float)));
    ReadFile("../input/input_y.bin", fileSize, *input2, (size_t)(inputYShape[0] * inputYShape[1] * sizeof(int32_t)));
    ReadFile("../input/input_z.bin", fileSize, *input3, (size_t)(inputZShape[0] * inputZShape[1] * sizeof(float)));
    INFO_LOG("inputXHostData[0]:%f, inputYHostData[0]:%d, inputZHostData[0]:%f", inputXHostData[0], inputYHostData[0], inputZHostData[0]);

    std::string str_gf, str_bf, str_gi;
    bool res_read = false;
    res_read = ReadFileEx("../input/growthFactor.bin", str_gf);
    res_read = ReadFileEx("../input/backoffFactor.bin", str_bf);
    res_read = ReadFileEx("../input/growthInterval.bin", str_gi);

    float growthFactor = std::stof(str_gf);
    float backoffFactor = std::stof(str_bf);
    int32_t growthInterval = std::stoi(str_gi);
    INFO_LOG("growthFactor:%f, backoffFactor:%f, growthInterval:%d", growthFactor, backoffFactor, growthInterval);
    INFO_LOG("Set input success");

    // 创建inputX Y Z aclTensor
    ret = CreateAclTensor(inputXHostData, inputXShape, &inputXDeviceAddr, aclDataType::ACL_FLOAT, &inputX);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputYHostData, inputYShape, &inputYDeviceAddr, aclDataType::ACL_INT32, &inputY);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputZHostData, inputZShape, &inputZDeviceAddr, aclDataType::ACL_FLOAT, &inputZ);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    // 创建outputA B aclTensor
    ret = CreateAclTensor(outputAHostData, outputAShape, &outputADeviceAddr, aclDataType::ACL_FLOAT, &outputA);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(outputBHostData, outputBShape, &outputBDeviceAddr, aclDataType::ACL_INT32, &outputB);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);

    // 3. 调用CANN自定义算子库API
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor;

    // 计算workspace大小并申请内存，将外部tiling参数传进算子
    ret = aclnnAmpUpdateScaleGetWorkspaceSize(
        inputX, inputY, inputZ, 
        growthFactor, backoffFactor, growthInterval,
        outputA, outputB, 
        &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAmpUpdateScaleGetWorkspaceSize failed. ERROR: %d, MSG: %s\n", ret, aclGetRecentErrMsg()); return FAILED);
    void *workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return FAILED;);
    }
    // 执行算子
    ret = aclnnAmpUpdateScale(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAmpUpdateScale failed. ERROR: %d\n", ret); return FAILED);

    // 4. （固定写法）同步等待任务执行结束
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return FAILED);

    // 5. 获取输出的值，将device侧内存上的结果拷贝至host侧，需要根据具体API的接口定义修改
    auto sizeA = GetShapeSize(outputAShape);
    std::vector<float> resultDataA(sizeA, 0);
    ret = aclrtMemcpy(resultDataA.data(), resultDataA.size() * sizeof(resultDataA[0]), outputADeviceAddr,
                      sizeA * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result A from device to host failed. ERROR: %d\n", ret); return FAILED);
    
    auto sizeB = GetShapeSize(outputBShape);
    std::vector<int64_t> resultDataB(sizeB, 0);
    ret = aclrtMemcpy(resultDataB.data(), resultDataB.size() * sizeof(resultDataB[0]), outputBDeviceAddr,
                      sizeB * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result B from device to host failed. ERROR: %d\n", ret); return FAILED);

    //写出数据，要输出两个变量
    float updated_scale = resultDataA[0];
    int32_t updated_growth_tracker = resultDataB[0];
    INFO_LOG("updated_scale:%f, updated_growth_tracker:%d", updated_scale, (int)updated_growth_tracker);
    
    void ** outputA_v=(void **)(&resultDataA);
    void ** outputB_v=(void **)(&resultDataB);
    size_t outputAShapeSize = outputAShape[0] * outputAShape[1];
    size_t outputBShapeSize = outputBShape[0] * outputBShape[1];
    ret = WriteFile("../output/output_A.bin", *outputA_v, outputAShapeSize * sizeof(float));
    ret &= WriteFile("../output/output_B.bin", *outputB_v, outputBShapeSize * sizeof(int32_t));
    if (!ret) {
        ERROR_LOG("Write output failed");
        return FAILED;
    }
    INFO_LOG("Write output success");

    // 6. 释放aclTensor，需要根据具体API的接口定义修改
    aclDestroyTensor(inputX);
    aclDestroyTensor(inputY);
    aclDestroyTensor(inputZ);
    aclDestroyTensor(outputA);
    aclDestroyTensor(outputB);

    // 7. 释放device资源，需要根据具体API的接口定义修改
    aclrtFree(inputXDeviceAddr);
    aclrtFree(inputYDeviceAddr);
    aclrtFree(inputZDeviceAddr);
    aclrtFree(outputADeviceAddr);
    aclrtFree(outputBDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return SUCCESS;
}
